import time
import datetime as dt
import requests
import pandas as pd

from tools.wrappers import deco_retry


@deco_retry(retry=50, retry_sleep=15)
def get_currency_historical_price(symbol='USDCNH'):
    today = dt.datetime.today()
    today = f'{today.year}_{today.month}_{today.day}'
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
    url = f'https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var _fx_s{symbol.lower()}{today}=/NewForexService.getDayKLine?symbol=fx_s{symbol.lower()}&_={today}'

    res = requests.get(url, headers=header, timeout=15)
    a = res.text.split('=("')
    b = a[1].split('");')
    c = b[0].split(',|')
    data_list = []
    for each_data in c:
        each_data = each_data.split(',')
        data_dict = {}
        data_dict['date'] = each_data[0]
        data_dict['open'] = float(each_data[1])
        data_dict['low'] = float(each_data[2])
        data_dict['high'] = float(each_data[3])
        data_dict['close'] = float(each_data[4])
        data_list.append(data_dict)
    df = pd.DataFrame(data_list)
    return df


@deco_retry(retry=50, retry_sleep=15)
def get_currency_latest_price(symbol='USDCNH'):
    timestamp_ = int(time.time() * 1000)
    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
              'Referer': 'https://finance.sina.com.cn/money/forex/hq/USDCNH.shtml'}
    url = f'https://hq.sinajs.cn/rn={timestamp_}list=fx_s{symbol.lower()}'
    res = requests.get(url, headers=header, timeout=15)
    a = res.text.split('="')
    b = a[1].split(',离岸人民币')
    c = b[0].split(',')
    latest_price = float(c[1])
    return latest_price


if __name__ == '__main__':
    get_currency_latest_price()